#include <SDL2/SDL.h>
#include <stdbool.h> // For bool, true, false
#include <stdlib.h>  // For rand() and srand()
#include <time.h>    // For time()

#define STEP_RATE_IN_MILLISECONDS  125
#define SNAKE_BLOCK_SIZE_IN_PIXELS 24
#define SNAKE_GAME_WIDTH  24U
#define SNAKE_GAME_HEIGHT 18U
#define SDL_WINDOW_WIDTH           (SNAKE_BLOCK_SIZE_IN_PIXELS * SNAKE_GAME_WIDTH)
#define SDL_WINDOW_HEIGHT          (SNAKE_BLOCK_SIZE_IN_PIXELS * SNAKE_GAME_HEIGHT)

#define SNAKE_MATRIX_SIZE (SNAKE_GAME_WIDTH * SNAKE_GAME_HEIGHT)
#define SNAKE_CELL_MAX_BITS 3U
#define SNAKE_CELL_SET_BITS  (~(~0u << SNAKE_CELL_MAX_BITS))
#define SHIFT(x, y) (((x) + ((y) * SNAKE_GAME_WIDTH)) * SNAKE_CELL_MAX_BITS)

static SDL_Joystick *joystick = NULL;

typedef enum{
    SNAKE_CELL_NOTHING = 0U,
    SNAKE_CELL_SRIGHT = 1U,
    SNAKE_CELL_SUP = 2U,
    SNAKE_CELL_SLEFT = 3U,
    SNAKE_CELL_SDOWN = 4U,
    SNAKE_CELL_FOOD = 5U
} SnakeCell;

typedef enum{
    SNAKE_DIR_RIGHT,
    SNAKE_DIR_UP,
    SNAKE_DIR_LEFT,
    SNAKE_DIR_DOWN
} SnakeDirection;

typedef struct{
    unsigned char cells[(SNAKE_MATRIX_SIZE * SNAKE_CELL_MAX_BITS) / 8U];
    char head_xpos;
    char head_ypos;
    char tail_xpos;
    char tail_ypos;
    char next_dir;
    char inhibit_tail_step;
    unsigned occupied_cells;
} SnakeContext;

typedef struct{
    SDL_Window *window;
    SDL_Renderer *renderer;
    SnakeContext snake_ctx;
    Uint32 last_step; // SDL2 Change: SDL_GetTicks() returns Uint32
} AppState;

SnakeCell snake_cell_at(const SnakeContext *ctx, char x, char y){
    const int shift = SHIFT(x, y);
    unsigned short range;
    SDL_memcpy(&range, ctx->cells + (shift / 8), sizeof(range));
    return (SnakeCell)((range >> (shift % 8)) & SNAKE_CELL_SET_BITS);
}

static void set_rect_xy_(SDL_Rect *r, short x, short y){
    r->x = x * SNAKE_BLOCK_SIZE_IN_PIXELS;
    r->y = y * SNAKE_BLOCK_SIZE_IN_PIXELS;
}

static void put_cell_at_(SnakeContext *ctx, char x, char y, SnakeCell ct){
    const int shift = SHIFT(x, y);
    const int adjust = shift % 8;
    unsigned char *const pos = ctx->cells + (shift / 8);
    unsigned short range;
    SDL_memcpy(&range, pos, sizeof(range));
    range &= ~(SNAKE_CELL_SET_BITS << adjust);
    range |= (ct & SNAKE_CELL_SET_BITS) << adjust;
    SDL_memcpy(pos, &range, sizeof(range));
}

static int are_cells_full_(SnakeContext *ctx){
    return ctx->occupied_cells == SNAKE_GAME_WIDTH * SNAKE_GAME_HEIGHT;
}

static void new_food_pos_(SnakeContext *ctx){
    while (true) {
        const char x = (char)(rand() % SNAKE_GAME_WIDTH);
        const char y = (char)(rand() % SNAKE_GAME_HEIGHT);
        if (snake_cell_at(ctx, x, y) == SNAKE_CELL_NOTHING) {
            put_cell_at_(ctx, x, y, SNAKE_CELL_FOOD);
            break;
        }
    }
}

void snake_initialize(SnakeContext *ctx){
    int i;
    SDL_memset(ctx->cells, 0, sizeof(ctx->cells));
    ctx->head_xpos = ctx->tail_xpos = SNAKE_GAME_WIDTH / 2;
    ctx->head_ypos = ctx->tail_ypos = SNAKE_GAME_HEIGHT / 2;
    ctx->next_dir = SNAKE_DIR_RIGHT;
    ctx->inhibit_tail_step = ctx->occupied_cells = 4;
    --ctx->occupied_cells;
    put_cell_at_(ctx, ctx->tail_xpos, ctx->tail_ypos, SNAKE_CELL_SRIGHT);
    for (i = 0; i < 4; i++) {
        new_food_pos_(ctx);
        ++ctx->occupied_cells;
    }
}

void snake_redir(SnakeContext *ctx, SnakeDirection dir){
    SnakeCell ct = snake_cell_at(ctx, ctx->head_xpos, ctx->head_ypos);
    if ((dir == SNAKE_DIR_RIGHT && ct != SNAKE_CELL_SLEFT) ||
        (dir == SNAKE_DIR_UP && ct != SNAKE_CELL_SDOWN) ||
        (dir == SNAKE_DIR_LEFT && ct != SNAKE_CELL_SRIGHT) ||
        (dir == SNAKE_DIR_DOWN && ct != SNAKE_CELL_SUP)) {
        ctx->next_dir = dir;
    }
}

static void wrap_around_(char *val, char max){
    if (*val < 0) {
        *val = max - 1;
    } else if (*val > max - 1) {
        *val = 0;
    }
}

void snake_step(SnakeContext *ctx){
    const SnakeCell dir_as_cell = (SnakeCell)(ctx->next_dir + 1);
    SnakeCell ct;
    char prev_xpos;
    char prev_ypos;
    /* Move tail forward */
    if (--ctx->inhibit_tail_step == 0) {
        ++ctx->inhibit_tail_step;
        ct = snake_cell_at(ctx, ctx->tail_xpos, ctx->tail_ypos);
        put_cell_at_(ctx, ctx->tail_xpos, ctx->tail_ypos, SNAKE_CELL_NOTHING);
        switch (ct) {
        case SNAKE_CELL_SRIGHT:
            ctx->tail_xpos++;
            break;
        case SNAKE_CELL_SUP:
            ctx->tail_ypos--;
            break;
        case SNAKE_CELL_SLEFT:
            ctx->tail_xpos--;
            break;
        case SNAKE_CELL_SDOWN:
            ctx->tail_ypos++;
            break;
        default:
            break;
        }
        wrap_around_(&ctx->tail_xpos, SNAKE_GAME_WIDTH);
        wrap_around_(&ctx->tail_ypos, SNAKE_GAME_HEIGHT);
    }
    /* Move head forward */
    prev_xpos = ctx->head_xpos;
    prev_ypos = ctx->head_ypos;
    switch (ctx->next_dir) {
    case SNAKE_DIR_RIGHT:
        ++ctx->head_xpos;
        break;
    case SNAKE_DIR_UP:
        --ctx->head_ypos;
        break;
    case SNAKE_DIR_LEFT:
        --ctx->head_xpos;
        break;
    case SNAKE_DIR_DOWN:
        ++ctx->head_ypos;
        break;
    default:
        break;
    }
    wrap_around_(&ctx->head_xpos, SNAKE_GAME_WIDTH);
    wrap_around_(&ctx->head_ypos, SNAKE_GAME_HEIGHT);
    /* Collisions */
    ct = snake_cell_at(ctx, ctx->head_xpos, ctx->head_ypos);
    if (ct != SNAKE_CELL_NOTHING && ct != SNAKE_CELL_FOOD) {
        snake_initialize(ctx);
        return;
    }
    put_cell_at_(ctx, prev_xpos, prev_ypos, dir_as_cell);
    put_cell_at_(ctx, ctx->head_xpos, ctx->head_ypos, dir_as_cell);
    if (ct == SNAKE_CELL_FOOD) {
        if (are_cells_full_(ctx)) {
            snake_initialize(ctx);
            return;
        }
        new_food_pos_(ctx);
        ++ctx->inhibit_tail_step;
        ++ctx->occupied_cells;
    }
}

static void handle_key_event_(SnakeContext *ctx, SDL_Scancode key_code, bool *running){
    switch (key_code) {
    /* Quit. */
    case SDL_SCANCODE_ESCAPE:
    case SDL_SCANCODE_Q:
        *running = false;
        break;
    /* Restart the game as if the program was launched. */
    case SDL_SCANCODE_R:
        snake_initialize(ctx);
        break;
    /* Decide new direction of the snake. */
    case SDL_SCANCODE_RIGHT:
        snake_redir(ctx, SNAKE_DIR_RIGHT);
        break;
    case SDL_SCANCODE_UP:
        snake_redir(ctx, SNAKE_DIR_UP);
        break;
    case SDL_SCANCODE_LEFT:
        snake_redir(ctx, SNAKE_DIR_LEFT);
        break;
    case SDL_SCANCODE_DOWN:
        snake_redir(ctx, SNAKE_DIR_DOWN);
        break;
    default:
        break;
    }
}

static void handle_hat_event_(SnakeContext *ctx, Uint8 hat) {
    switch (hat) {
    case SDL_HAT_RIGHT:
        snake_redir(ctx, SNAKE_DIR_RIGHT);
        break;
    case SDL_HAT_UP:
        snake_redir(ctx, SNAKE_DIR_UP);
        break;
    case SDL_HAT_LEFT:
        snake_redir(ctx, SNAKE_DIR_LEFT);
        break;
    case SDL_HAT_DOWN:
        snake_redir(ctx, SNAKE_DIR_DOWN);
        break;
    default:
        break;
    }
}

int main(int argc, char *argv[])
{
    // --- 初始化 ---
    if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_JOYSTICK) < 0) {
        SDL_Log("Couldn't initialize SDL: %s", SDL_GetError());
        return 1;
    }

    srand((unsigned)time(NULL));

    AppState as;
    SDL_memset(&as, 0, sizeof(AppState));

    as.window = SDL_CreateWindow("Snake Game (SDL2)", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, SDL_WINDOW_WIDTH, SDL_WINDOW_HEIGHT, 0);
    if (!as.window) {
        SDL_Log("Window could not be created! SDL_Error: %s", SDL_GetError());
        SDL_Quit();
        return 1;
    }

    as.renderer = SDL_CreateRenderer(as.window, -1, SDL_RENDERER_ACCELERATED);
    if (!as.renderer) {
        SDL_Log("Renderer could not be created! SDL_Error: %s", SDL_GetError());
        SDL_DestroyWindow(as.window);
        SDL_Quit();
        return 1;
    }

    snake_initialize(&as.snake_ctx);
    as.last_step = SDL_GetTicks();

    bool running = true;
    SDL_Event event;

    while (running) {
        while (SDL_PollEvent(&event)) {
            switch (event.type) {
            case SDL_QUIT:
                running = false;
                break;
            case SDL_JOYDEVICEADDED:
                if (joystick == NULL) {
                    joystick = SDL_JoystickOpen(event.jdevice.which);
                    if (!joystick) {
                        SDL_Log("Failed to open joystick ID %d: %s", event.jdevice.which, SDL_GetError());
                    }
                }
                break;
            case SDL_JOYDEVICEREMOVED:
                if (joystick && (SDL_JoystickInstanceID(joystick) == event.jdevice.which)) {
                    SDL_JoystickClose(joystick);
                    joystick = NULL;
                }
                break;
            case SDL_JOYHATMOTION:
                handle_hat_event_(&as.snake_ctx, event.jhat.value);
                break;
            case SDL_KEYDOWN:
                handle_key_event_(&as.snake_ctx, event.key.keysym.scancode, &running);
                break;
            }
        }

        const Uint32 now = SDL_GetTicks();
        while ((now - as.last_step) >= STEP_RATE_IN_MILLISECONDS) {
            snake_step(&as.snake_ctx);
            as.last_step += STEP_RATE_IN_MILLISECONDS;
        }

        SDL_Rect r;
        r.w = r.h = SNAKE_BLOCK_SIZE_IN_PIXELS;

        SDL_SetRenderDrawColor(as.renderer, 0, 0, 0, SDL_ALPHA_OPAQUE);
        SDL_RenderClear(as.renderer);

        for (unsigned i = 0; i < SNAKE_GAME_WIDTH; i++) {
            for (unsigned j = 0; j < SNAKE_GAME_HEIGHT; j++) {
                int ct = snake_cell_at(&as.snake_ctx, i, j);
                if (ct == SNAKE_CELL_NOTHING)
                    continue;

                set_rect_xy_(&r, i, j);
                if (ct == SNAKE_CELL_FOOD)
                    SDL_SetRenderDrawColor(as.renderer, 80, 80, 255, SDL_ALPHA_OPAQUE);
                else /* body */
                    SDL_SetRenderDrawColor(as.renderer, 0, 128, 0, SDL_ALPHA_OPAQUE);
                SDL_RenderFillRect(as.renderer, &r);
            }
        }

        SDL_SetRenderDrawColor(as.renderer, 255, 255, 0, SDL_ALPHA_OPAQUE);
        set_rect_xy_(&r, as.snake_ctx.head_xpos, as.snake_ctx.head_ypos);
        SDL_RenderFillRect(as.renderer, &r);

        SDL_RenderPresent(as.renderer);
    }

    if (joystick) {
        SDL_JoystickClose(joystick);
    }
    SDL_DestroyRenderer(as.renderer);
    SDL_DestroyWindow(as.window);
    SDL_Quit();

    return 0;
}